package cn.cit.training.data.service.impl;

import cn.cit.training.data.common.utils.BlankUtil;
import cn.cit.training.data.entity.CitData;
import cn.cit.training.data.mapper.CitDataMapper;
import cn.cit.training.data.vo.ChartInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import cn.cit.training.data.service.CitDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Map;

/**
 * <p>
 * 数据表 服务实现类
 * </p>
 *
 * @author
 * @since 2020-09-01
 */
@Service
public class CitDataServiceImpl extends ServiceImpl<CitDataMapper, CitData> implements CitDataService {

    @Override
    public CitData getOneById(int id) {
        return super.getById(id);
    }

    @Override
    public CitData getOneByPId(int pId) {
        QueryWrapper<CitData> wrapper = new QueryWrapper<>();
        wrapper.eq("p_id", pId);
        return super.getOne(wrapper);
    }

    @Override
    public IPage<CitData> getCitDataPage(int pageSize, int currentPage, String field, int min, int max) {
        IPage<CitData> citDataPage;

        // 组装page分页查询条件
        Page<CitData> page = new Page<>(currentPage, pageSize);

        // 判断平台名称是否为空
        if (BlankUtil.isNotBlank(field)) {
            // 不为空 通过平台名称查询
            QueryWrapper<CitData> wrapper = new QueryWrapper<>();
            wrapper.ge(field, min);
            wrapper.le(field, max);
            citDataPage = this.page(page, wrapper);
        } else {
            // 为空 直接分页查询
            citDataPage =  this.page(page);
        }

        return citDataPage;
    }

    @Override
    public ChartInfo getChartData(int min, int max) {
        // 不为空 通过平台名称查询
        QueryWrapper<CitData> wrapper = new QueryWrapper<>();
        wrapper.ge("year", min);
        wrapper.le("year", max);
        wrapper.select("sum(t_duration) as totalDuration ");
        Map<String, Object> map = this.getMap(wrapper);
        int totalDuration = Integer.valueOf(String.valueOf(map.get("totalDuration")));
        wrapper.select("sum(t_travel) as totalTravel ");
        map = this.getMap(wrapper);

        int totalTravel = Integer.valueOf(String.valueOf(map.get("totalTravel")));
        ChartInfo chartInfo = new ChartInfo();
        chartInfo.setTotalTravel(totalTravel);
        chartInfo.setTotalDuration(totalDuration);

        return chartInfo;
    }

    @Override
    public boolean deleteCitData(int id) {
        return super.removeById(id);
    }

    @Override
    public boolean updateCitData(CitData citData) {
        return super.updateById(citData);
    }
}
